/**
 * FIFOFixTimeCountQueue.java
 */
package com.mht2017.common.dto;

import java.util.ArrayDeque;

/**
 * 存放指定时间的队列(只记录存放时候的时间戳，而不存储数据)，超过时间的记录将被移除<br/>
 * 移除规则：仅当有新元素加入或者读取数字的时候才触发移除算法
 *
 * @author yutong.xiao
 * @date 2017年7月18日 下午3:05:54
 */
public class FIFOFixTimeCountQueue {

	private final long fixTimeDelta;
	private final ArrayDeque<Long> deque = new ArrayDeque<>();;

	public FIFOFixTimeCountQueue(long fixTimeDeltaInMills) {
		fixTimeDelta = fixTimeDeltaInMills;
	}

	public synchronized void add() {
		check();
		deque.addLast(System.currentTimeMillis());
	}

	public synchronized void add(int count) {
		if (count > 0) {
			check();
			long current = System.currentTimeMillis();
			for (int i = 0; i < count; i++) {
				deque.addLast(current);
			}
		}
	}

	private void check() {
		long now = System.currentTimeMillis();
		while (deque.isEmpty() == false) {
			Long first = deque.peekFirst();
			if (null != first && now - first.longValue() > fixTimeDelta) {
				deque.removeFirst();
			} else {
				break;
			}
		}
	}

	public int getActualSize() {
		check();
		return deque.size();
	}

	@Override
	public String toString() {
		return String.format("fixTimeDelta: '%s', queue: '%s'", fixTimeDelta, deque);
	}

}
